//
//  DERRegisterPortalViewController.swift
//  ezyform
//
//  Created by MoennigQ on 14/4/20.
//  Copyright © 2020 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import WebKit

class DERRegisterPortalViewController: BaseViewController {
    let withoutNetworkView = DatalLoadFaildView()
    var aemoURL: URL!
    var wkWebView : WKWebView!
    var progBar :UIProgressView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadData()
    }
    func loadData(){
        self.view.backgroundColor = .white
        let urlString = "https://aemo.com.au/energy-systems/electricity/der-register"
        
        guard let url = URL(string: urlString) else{
            return
        }
        self.aemoURL = url
        let request = NSMutableURLRequest(url: url)
        request.setValue("iOS", forHTTPHeaderField: "X-API-MOBILE-TYPE")
        // 用户交互信息管理
        let userContent = WKUserContentController()
        
        let config = WKWebViewConfiguration()
        config.userContentController = userContent
        
        wkWebView = WKWebView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), configuration: config)
        wkWebView.backgroundColor = UIColor.clear
        wkWebView.navigationDelegate = self
        self.view.addSubview(wkWebView)
        wkWebView.snp.makeConstraints { (make) in
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
            make.left.right.bottom.equalToSuperview()
        }
        withoutNetworkView.retryBtn.addTarget(self, action: #selector(retryBtnClick), for: UIControl.Event.touchUpInside)
        //
        withoutNetworkView.isHidden = true
        self.view.addSubview(withoutNetworkView)
        withoutNetworkView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.wkWebView)
        }
        //process bar
        progBar = UIProgressView()
        progBar.progress = 0.0
        progBar.tintColor = UIColor(rgb: 0x3BADFF)
        progBar.backgroundColor = .white
        self.view.addSubview(progBar)
        progBar.snp.makeConstraints { (make) in
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
            make.left.right.equalToSuperview()
            make.height.equalTo(3)
        }
        if Connectivity.isConnectedToInternet {
            progBar.alpha = 1.0
            wkWebView.load(request as URLRequest)
        }else{
            self.showWithoutInternetBackView()
        }
        self.wkWebView.addObserver(self, forKeyPath: "title", options: NSKeyValueObservingOptions.new, context: nil)
        self.wkWebView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)
    }
    //没有网络
    func showWithoutInternetBackView(){
        self.title = ""
        self.withoutNetworkView.isHidden = false
        self.wkWebView.isHidden = true
        
    }
    @objc func retryBtnClick(){
        if let url = self.aemoURL{
            let request = NSMutableURLRequest(url: url)
            self.wkWebView.load(request as URLRequest)
        }
        
    }
    
    //
    func showWebView(){
        self.withoutNetworkView.isHidden = true
        self.wkWebView.isHidden = false
    }
    override func backToPre() {
        //WKWebView中内部返回
        if self.wkWebView.canGoBack {
            
            if !self.withoutNetworkView.isHidden{
                _ = self.navigationController?.popViewController(animated: false)
            }else{
                self.wkWebView.goBack()
            }
            
        }else{
            _ = self.navigationController?.popViewController(animated: false)
        }
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if keyPath == "estimatedProgress" {
            self.progBar.alpha = 1.0
            //            print(wkWebView.estimatedProgress)
            progBar.setProgress(Float(wkWebView.estimatedProgress), animated: true)
            //Max value of process bar is 1.0
            if(self.wkWebView.estimatedProgress >= 1.0) {
                UIView.animate(withDuration: 0.3, delay: 0.1, options: UIView.AnimationOptions.curveEaseInOut, animations: { () -> Void in
                    self.progBar.alpha = 0.0
                }, completion: { (finished:Bool) -> Void in
                    self.progBar.progress = 0.0
                })
            }
        }else if keyPath == "title" {
            if object as? WKWebView == self.wkWebView {
                self.title = self.wkWebView.title ?? ""
            }
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        self.tabBarController?.tabBar.isHidden = true
        self.navigationController?.setNavigationBarHidden(false, animated: false)
    }
    deinit {
        if self.isViewDidLoad{
            //1.remove observer
            self.wkWebView.removeObserver(self, forKeyPath: "title")
            self.wkWebView.removeObserver(self, forKeyPath: "estimatedProgress")
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        DebugLog("\(self) didReceiveMemoryWarning")
    }
}
extension DERRegisterPortalViewController: WKNavigationDelegate{
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        
    }
    //此代理方法必须实现，否则假网络时不会调用didFailProvisionalNavigation
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        decisionHandler(WKNavigationActionPolicy.allow)
    }
    @available(iOS 13.0, *)
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, preferences: WKWebpagePreferences, decisionHandler: @escaping (WKNavigationActionPolicy, WKWebpagePreferences) -> Void) {
        //在发送请求之前，决定是否跳转
        decisionHandler(WKNavigationActionPolicy.allow, preferences)
    }
    //当Web视图开始接收Web内容时调用
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        self.showWebView()
    }
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        DebugLog("加载完毕")
    }
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
//        let urlError = error as NSError
//                print(urlError.code)
//                print(urlError.localizedDescription)
//        if urlError.code == -1004 || urlError.code == -1009 || urlError.code == -1001{//-1004:无法连接到主机;-1009：The Internet connection appears to be offline.
//            self.showWithoutInternetBackView()
//        }else if urlError.code == -1001 {//请求超时
//            self.showTimeOutBackView()
//        }
        self.showWithoutInternetBackView()
    }
}
